<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="结算编码" prop="settlementCode">
        <el-input
            v-model="queryParams.settlementCode"
            placeholder="请输入结算编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合作方编码" prop="partnerCode" label-width="120px">
        <el-input
            v-model="queryParams.partnerCode"
            placeholder="请输入合作方编码"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结算方式" prop="settlementMethod">
        <el-select v-model="queryParams.settlementMethod" placeholder="请选择结算方式" clearable>
          <el-option
              v-for="dict in settlement_ways"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['record:record:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordList" @selection-change="handleSelectionChange" style="margin-top: 15px; height: 80%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="结算编码" align="center" prop="settlementCode" />
      <el-table-column label="合作方编码" align="center" prop="partnerCode" />
      <el-table-column label="合作方类型" align="center" prop="partnerType" />
      <el-table-column label="结算总金额(元)" align="center" prop="settlementAmount" />
      <!-- <el-table-column label="货币单位" align="center" prop="currencyUnit" /> -->
      <!-- <el-table-column label="结算方式" align="center" prop="settlementMethod">
        <template #default="scope">
          <dict-tag :options="settlement_ways" :value="scope.row.settlementMethod"/>
        </template>
      </el-table-column> -->
      <el-table-column label="协议编码" align="center" prop="agreementCode" />
      <el-table-column label="创建日期" align="center" prop="startDate" width="180">
  <template #default="scope">
    <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
  </template>
</el-table-column>
      
      
      
     
      <el-table-column label="实际支付日期" align="center" prop="paymentDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="结算状态" align="center" prop="settlementStatus" /> -->
      <el-table-column label="结算状态" align="center" prop="settlementStatus">
        <template #default="scope">
          <el-tag :type="primary" disable-transitions>
            {{ scope.row.settlementStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
       <template #default="scope">
         <div style="display: flex; justify-content: center;">
           <el-button
          link
          type="primary"
          icon="View"
          @click="handleDetail(scope.row)"
          v-hasPermi="['record:record:detail']"
      >详情</el-button>
      <el-button
        link
        type="danger"
        icon="Delete"
        @click="handleDelete(scope.row)"
        :disabled="scope.row.settlementStatus !== '待确认'"
      >删除</el-button>
    </div>
  </template>
</el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改结算记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合作方编码" prop="partnerCode">
          <el-input v-model="form.partnerCode" placeholder="请输入合作方编码" />
        </el-form-item>
        <el-form-item label="结算总金额" prop="settlementAmount">
          <el-input v-model="form.settlementAmount" placeholder="请输入结算总金额" />
        </el-form-item>  
        <el-form-item label="货币单位" prop="currencyUnit">
          <el-input v-model="form.currencyUnit" placeholder="请输入货币单位" />
        </el-form-item>
        <!-- <el-form-item label="结算方式" prop="settlementMethod">
          <el-select v-model="form.settlementMethod" placeholder="请选择结算方式">
            <el-option
                v-for="dict in settlement_ways"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
      
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">结算详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddSettlementDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteSettlementDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="settlementDetailList" :row-class-name="rowSettlementDetailIndex" @selection-change="handleSettlementDetailSelectionChange" ref="settlementDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结算记录详情对话框 -->
<el-dialog :title="detailTitle" v-model="detailOpen" width="800px" append-to-body>
  <el-form :model="detailForm" label-width="120px" disabled>
    <el-form-item label="结算编码">
      <el-input v-model="detailForm.settlementCode" />
    </el-form-item>
    <el-form-item label="合作方编码">
      <el-input v-model="detailForm.partnerCode" />
    </el-form-item>
    <el-form-item label="结算总金额">
      <el-input v-model="detailForm.settlementAmount" />
    </el-form-item>
    <!-- <el-form-item label="货币单位">
      <el-input v-model="detailForm.currencyUnit" />
    </el-form-item> -->
    <el-form-item label="协议编码">
      <el-input v-model="detailForm.agreementCode" />
    </el-form-item>
    <el-form-item label="创建日期">
      <el-input v-model="detailForm.startDate" />
    </el-form-item>
    <el-form-item label="实际支付日期">
      <el-input v-model="detailForm.paymentDate" />
    </el-form-item>
    <el-form-item label="结算状态">
      <el-input v-model="detailForm.settlementStatus" />
    </el-form-item>
    <el-form-item label="备注信息">
      <el-input v-model="detailForm.remark" type="textarea" />
    </el-form-item>

    <!-- 结算明细表格 -->
    <el-divider content-position="center">结算明细</el-divider>
    <el-table :data="detailSettlementDetailList" border style="width: 100%; margin-top: 10px;">
      <el-table-column label="序号" align="center" prop="index" width="80" />
      <el-table-column label="订单编码" align="center" prop="orderCode" />
      <el-table-column label="结算单编码" align="center" prop="settlementCode" />
      <el-table-column label="订单金额" align="center" prop="orderAmount">
  <template #default="scope">
    <span>{{ scope.row.orderAmount !== undefined ? scope.row.orderAmount.toFixed(2) : '-' }}</span>
  </template>
</el-table-column>
      
    </el-table>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="detailOpen = false">关 闭</el-button>
    </div>
  </template>
</el-dialog>
  </div>
</template>

<script setup name="Record">
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/settled/record";
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance();
const { settlement_ways } = proxy.useDict('settlement_ways');

const recordList = ref([]);
const settlementDetailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedSettlementDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const detailOpen = ref(false);
const detailTitle = ref("");
const detailForm = ref({});
const detailSettlementDetailList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    settlementCode: null,
    partnerCode: null,
    settlementMethod: null,
    settlementStatus: null,
  },
  rules: {
    partnerCode: [
      { required: true, message: "合作方编码不能为空", trigger: "blur" }
    ],
    settlementAmount: [
      { required: true, message: "结算总金额不能为空", trigger: "blur" }
    ],
    settlementMethod: [
      { required: true, message: "结算方式不能为空", trigger: "change" }
    ],
    agreementCode: [
      { required: true, message: "协议编码不能为空", trigger: "blur" }
    ],
    startDate: [
      { required: true, message: "结算起始时间不能为空", trigger: "blur" }
    ],
    endDate: [
      { required: true, message: "结算结束时间不能为空", trigger: "blur" }
    ],
    currencyUnit: [
      { required: true, message: "货币单位不能为空", trigger: "blur" }
    ],

    settlementStatus: [
      { required: true, message: "结算状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询结算记录列表 */
function getList() {
  loading.value = true;
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows.map(row => ({
      ...row,
      partnerType: getPartnerType(row.partnerCode)
    })).sort((a, b) => {
      // 将 startDate 转换为 Date 对象进行比较
      return new Date(b.startDate) - new Date(a.startDate);
    });
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    settlementCode: null,
    partnerCode: null,
    settlementType: null,
    settlementAmount: null,
    settlementMethod: null,
    agreementCode: null,
    startDate: null,
    endDate: null,
    currencyUnit: null,

    paymentDate: null,
    settlementStatus: null,
    creator: null,
    modifyTime: null,
    lastModifiedBy: null,
    remark: null
  };
  settlementDetailList.value = [];
  proxy.resetForm("recordRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.settlementCode);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加结算记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _settlementCode = row.settlementCode || ids.value;
  getRecord(_settlementCode).then(response => {
    form.value = response.data;
    settlementDetailList.value = response.data.settlementDetailList;
    open.value = true;
    title.value = "修改结算记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      form.value.settlementDetailList = settlementDetailList.value;
      if (form.value.settlementCode != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _settlementCode = row.settlementCode;
  proxy.$modal.confirm('是否确认删除结算记录编号为"' + _settlementCode + '"的数据项？').then(function() {
    return delRecord(_settlementCode);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 结算详情序号 */
function rowSettlementDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 结算详情添加按钮操作 */
function handleAddSettlementDetail() {
  let obj = {};
  settlementDetailList.value.push(obj);
}

/** 结算详情删除按钮操作 */
function handleDeleteSettlementDetail() {
  if (checkedSettlementDetail.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的结算详情数据");
  } else {
    const settlementDetails = settlementDetailList.value;
    const checkedSettlementDetails = checkedSettlementDetail.value;
    settlementDetailList.value = settlementDetails.filter(function(item) {
      return checkedSettlementDetails.indexOf(item.index) == -1;
    });
  }
}

/** 复选框选中数据 */
function handleSettlementDetailSelectionChange(selection) {
  checkedSettlementDetail.value = selection.map(item => item.index);
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('record/record/export', {
    ...queryParams.value
  }, `record_${new Date().getTime()}.xlsx`);
}



/** 详情按钮操作 */
function handleDetail(row) {
  getRecord(row.settlementCode).then(response => {
    detailForm.value = response.data;
    console.log(response.data);
    // 获取结算明细数据
    detailSettlementDetailList.value = response.data.settlementDetailList.map((detail, index) => ({
      ...detail,
      index: index + 1 // 添加序号
    }));
    detailTitle.value = `结算记录详情 - ${row.settlementCode}`;
    detailOpen.value = true;
  });
}

function parseTime(time, format) {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return format.replace('{y}', year)
              .replace('{m}', month)
              .replace('{d}', day)
              .replace('{h}', hours)
              .replace('{i}', minutes)
              .replace('{s}', seconds);
}

/** 根据合作方编码获取合作方类型 */
function getPartnerType(partnerCode) {
  if (partnerCode.startsWith('DEALER')) {
    return '经销商';
  } else if (partnerCode.startsWith('LEADER')) {
    return '团长';
  }else if (partnerCode.startsWith('BLOGGER')) {
    return '博主';
  }else if (partnerCode.startsWith('LOGISITICS')) {
    return '物流商';
  }else if (partnerCode.startsWith('SUPPLY')) {
    return '供货商';
  }else if (partnerCode.startsWith('S')) {
      return '供货商';
  }else if (partnerCode.startsWith('1')) {
      return '经销商';
  }else if (partnerCode.startsWith('2')) {
      return '经销商';
  }else if (partnerCode.startsWith('3')) {
      return '经销商';
  }else if (partnerCode.startsWith('4')) {
      return '经销商';
  }else {
    return '未知类型';
  }
}


getList();
</script>